// Copyright (C) 2025, ZWSOFT Co., LTD.(Guangzhou)
// Licensed under the MIT License. See LICENSE in the project root for license information.

using Microsoft.Extensions.DependencyInjection;
using System.Windows;
using System.Windows.Controls;

namespace TestClient.ViewModel
{
    public interface ITestItem
    {
        string Name { get; }
        object Content { get; }
    }

    public class TestItem<TPage, TViewModel> : ITestItem
        where TPage : UserControl, new()
        where TViewModel : class
    {
        public string Name { get; init; }

        private readonly Lazy<TViewModel> _viewModel;
        private readonly Lazy<TPage> _page;

        public TestItem(string name)
        {
            Name = name;
            _viewModel = new(() =>
            {
                var app = Application.Current as App;
                return app?.Services?.GetService<TViewModel>()
                    ?? throw new InvalidOperationException($"ViewModel {typeof(TViewModel).Name} is not registered");
            });
            _page = new(() =>
            {
                var vm = _viewModel.Value;
                var page = new TPage
                {
                    DataContext = vm
                };
                return page;
            });
        }

        public object Content => _page.Value;
    }
}
